﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace Coslen.TahorCRM.Security
{
    /// <summary>
    /// Source: 
    /// 1. http://stackoverflow.com/questions/1771165/cookie-is-not-deleted
    /// 2. http://msdn.microsoft.com/en-us/library/ms178195.aspx
    /// </summary>
    public class CookieHelper
    {
        public static string AuthCookieKey = ".MVCAUTH";

        public static void AddCookie(string key, string value, DateTime expires)
        {
            var httpContext = new HttpContextWrapper(HttpContext.Current);
            var _request = httpContext.Request;
            var _response = httpContext.Response;

            HttpCookie cookie = new HttpCookie(key, value) { Expires = expires };
            _response.Cookies.Set(cookie);
        }

        public static void RemoveCookie(string key)
        {
            var httpContext = new HttpContextWrapper(HttpContext.Current);
            var _request = httpContext.Request;
            var _response = httpContext.Response;

            HttpCookie cookie = new HttpCookie(key, null) { Expires = DateTime.Now.AddDays(-1) };
            _response.Cookies.Set(cookie);
        }

        public static HttpCookie GetCookie(string key)
        {
            var httpContext = new HttpContextWrapper(HttpContext.Current);
            var _request = httpContext.Request;
            var _response = httpContext.Response;

            return _request.Cookies[key];
        }

        public static bool Exists(string key)
        {
            var httpContext = new HttpContextWrapper(HttpContext.Current);
            var _request = httpContext.Request;
            var _response = httpContext.Response;
            return _request.Cookies[key] != null;
        }

        public static void Clear(string key)
        {
            var httpContext = new HttpContextWrapper(HttpContext.Current);
            var _response = httpContext.Response;

            HttpCookie cookie = new HttpCookie(key)
            {
                Value = null,
                Expires = DateTime.Now.AddDays(-1) // or any other time in the past 
            };
            _response.Cookies.Set(cookie);
        } 
    }
}
